var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken");
const { sercetKey } = require("./../config");

router.get("/", (req, res) => {
  res.send("路由模块模拟");
});

router.get("/get", (req, res) => {
  console.log(req.query); // get请求通过req.query方式拿到一个包含所有参数的对象
  res.send(req.query);
});

router.post("/post", (req, res) => {
  console.log(req);
  console.log(req.body);
  res.send(req.body);
});

// router.post("/login", (req, res) => {
//   if (req.body.username !== "admin" || req.body.password !== "123456") {
//     return res.send({ status: 1, mes: "登录失败" });
//   }
//   req.session.user = req.body;
//   req.session.isLogin = true;
//   console.log(req.session);

//   res.send({ status: 0, mes: "登录成功！" });
// });

// router.get("/username", (req, res) => {
//   console.log(req.session);
//   if (!req.session.isLogin) {
//     return res.send({ status: 1, mes: "请先登录！" });
//   }

//   res.send({ status: 0, mes: "success", username: req.session.user.username });
// });

// router.post("/logout", (req, res) => {
//   req.session.destroy();
//   res.send({ status: 0, mes: "success" });
// });

router.post("/login", (req, res) => {
  if (req.body.username !== "admin" || req.body.password !== "123456") {
    return res.send({ status: 1, mes: "登录失败" });
  }
  const tokenStr = jwt.sign(
    { username: req.body.username },
    sercetKey,
    { expiresIn: "30s" }
  );

  res.send({ status: 0, mes: "登录成功！", token: tokenStr });
});

router.get("/username", (req, res) => {
  console.log(req.session);
  if (!req.session.isLogin) {
    return res.send({ status: 1, mes: "请先登录！" });
  }

  res.send({ status: 0, mes: "success", username: req.session.user.username });
});

router.post("/logout", (req, res) => {
  req.session.destroy();
  res.send({ status: 0, mes: "success" });
});

module.exports = router;
